package com.zwr.sheller.customer.Service.Impl;

import com.zwr.sheller.core.common.WQQBusinessException;
import com.zwr.sheller.core.common.WQQExceptionCode;
import com.zwr.sheller.core.pojo.*;
import com.zwr.sheller.core.util.JsonUtil;
import com.zwr.sheller.core.util.RedisUtil;
import com.zwr.sheller.customer.Service.StoreShellerIndexService;
import com.zwr.sheller.customer.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @Author: 18032
 * @Date: 10:21 2022/1/12
 */
@Service
public class StoreShellerIndexServiceImpl implements StoreShellerIndexService {

    @Autowired(required = false)
    RedisTemplate<String, Object> redisTemplate;

    @Autowired(required = false)
    StoreMapper storeMapper;

    @Autowired(required = false)
    SignMapper signMapper;

    @Autowired(required = false)
    NavigationBarMapper navigationBarMapper;

    @Autowired(required = false)
    ItemMapper itemMapper;

    @Autowired(required = false)
    GoodsMapper goodsMapper;


    @Override
    public List<Map<String, Object>> indexData(Long id) throws WQQBusinessException {
        //1.查询到店铺的信息装入storeMap中 TODO 1.1 首先在redis中查询


        //1.2 如果redis没有就远程通信数据库中查询
        Map<String, Object> storeMap = selectStoreBasicMessage(id);
        //Todo 1.2.1 查询店铺今日销量,查询店铺累计销量,本月更新商品装入storeMap中
        //1.2.2 数据库查询店招商品
        Example example = new Example(Sign.class);
        example.createCriteria().andEqualTo("storeId", id);
        example.setOrderByClause("sign_order ASC");
        List<Sign> signs = signMapper.selectByExample(example);
        HashMap<String, Object> signMap = new HashMap<>(2);
        signMap.put("signs", signs);

        //1.2.3 数据库查询所有的分类
        Example navigationExample = new Example(NavigationBar.class);
        navigationExample.createCriteria().andEqualTo("storeId", id);
        List<NavigationBar> navigationBars = navigationBarMapper.selectByExample(navigationExample);
        HashMap<String, Object> navigationBarMap = new HashMap<>();
        navigationBarMap.put("navigationBars", navigationBars);
        if (navigationBars == null) {
            throw new WQQBusinessException(WQQExceptionCode.NO_NAVIDATA);
        }
        //查询出第一个分类的所有商品
        Long itemId = navigationBars.get(0).getItemId();
        Item item = itemMapper.selectByPrimaryKey(itemId);
        if (item == null) {
            throw new WQQBusinessException(WQQExceptionCode.NO_ITEM);
        }
        Integer itemRank = item.getItemRank();
        Example itemExample = new Example(Goods.class);
        List<Goods> goods = new ArrayList<>();
        switch (itemRank) {
            case 1:
                itemExample.createCriteria().andEqualTo("goodsFirstItemId", itemId);
                break;
            case 2:
                itemExample.createCriteria().andEqualTo("goodsSecondItemId", itemId);
                break;
            default:
                itemExample.createCriteria().andEqualTo("goodsThirdItemId", itemId);
        }
        goods = goodsMapper.selectByExample(itemExample);
        if (goods == null) {
            throw new WQQBusinessException(WQQExceptionCode.NO_GOOD);
        }
        Map<String, Object> goodsMap = new HashMap<>();
        goodsMap.put("goods", goods);
        //Todo 1.3 查询成功,将数据写入redis

        //1.4 将几个map写入List中
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(storeMap);
        list.add(signMap);
        list.add(navigationBarMap);
        list.add(goodsMap);
        return list;
    }

    @Override
    public List<Goods> selectAllShellerGoods(Long storeId) throws WQQBusinessException {
        //Todo 1. redis查询商品
        //2.没有就从数据库中查询
        Example example = new Example(Goods.class);
        example.createCriteria().andEqualTo("storeId", storeId);
        List<Goods> goods = goodsMapper.selectByExample(example);
        if (goods == null) {
            throw new WQQBusinessException(WQQExceptionCode.NO_GOOD);
        }
        //Todo 3.数据库的商品写入redis
        return goods;
    }

    @Override
    public List<Map<String, Object>> selectNewOrSaleGoods(Long storeId, Integer choose) throws WQQBusinessException {
        //Todo 首先在Redis中查询
        //choose为0,按照最新上架排序
        List<Map<String, Object>> goodsList = new ArrayList<>();
        if (choose == 0) {
            goodsList = goodsMapper.selectByShelfTime(storeId);
        } else if (choose == 1) {
            //choose为1,按照最高折扣排序
            goodsList = goodsMapper.selectByDiscount(storeId);
        } else if (choose == 2) {
            //Todo choose为2,按照销量排序
            return null;
        } else if (choose == 3) {
            // choose为3,按照价格排序
            goodsList = goodsMapper.selectByPrice(storeId);
        } else {
            throw new WQQBusinessException(WQQExceptionCode.WRONG_CHOOSE);
        }
        if (goodsList == null) {
            throw new WQQBusinessException(WQQExceptionCode.NO_GOOD);
        }
        return goodsList;
    }

    @Override
    public List<Map<String,Object>> selectByOption(Long storeId, Integer choose, Double lowPrice, Double highPrice) throws WQQBusinessException {
        if (choose!= 0 && choose!= 1 && choose!= 2){
            throw new WQQBusinessException(WQQExceptionCode.WRONG_CHOOSE);
        }
        //choose为0,热卖,choose为1,新品,choose为2,推荐
        List<Map<String, Object>> list = goodsMapper.selectByOption(storeId, choose, lowPrice, highPrice);
        if (list == null){
            throw new WQQBusinessException(WQQExceptionCode.NO_GOOD);
        }

        return list;
    }

    @Override
    public Map<String, Object> introduceStore(Long storeId) throws WQQBusinessException {
        //1.数据库中查店家信息
        Map<String, Object> storeMap = selectStoreBasicMessage(storeId);
        Store store = storeMapper.selectByPrimaryKey(storeId);
        if (store == null) {
            throw new WQQBusinessException(WQQExceptionCode.FAILED_SELECT_STORE);
        }

        //2.基本信息放入storeMap中
        storeMap.put("openTIme", store.getStoreOpenTime());
        storeMap.put("storeAddress", store.getStoreAddress());
        storeMap.put("honestMoney", "500.00");
        storeMap.put("servicePhone", store.getStorePhone());
        storeMap.put("storeDesc", store.getStoreDesc());

        //Todo 3.累计销量放入storeMap中
        storeMap.put("totalSellNum", 0);
        storeMap.put("monthSellNum", 0);
        storeMap.put("todaySellNum", 0);
        storeMap.put("monthNewSellNum", 0);
        storeMap.put("storeFans", 0);
        storeMap.put("totalRefund", 0);
        return storeMap;
    }

    @Override
    public List<Map<String,Object>> oneSort(Long storeId) throws WQQBusinessException {
        //查询所有的bar
        List<Map<String, Object>> list = storeMapper.selectOneSort(storeId);
        if (list == null){
            throw new WQQBusinessException(WQQExceptionCode.NO_FIELD);
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> twoAndThreeSort(Long storeId, Long itemId) throws WQQBusinessException {
        List<Map<String, Object>> list = storeMapper.selectTwoSort(storeId, itemId);
        for (Map<String, Object> map : list) {
            System.out.println("map:"+map);
            map.put("threeSort",storeMapper.selectThreeSort(storeId,Long.valueOf(map.get("item_id").toString())));
        }
        return list;
    }

    /**
     * 数据库查询店家信息
     *
     * @param storeId
     * @return
     */
    @Override
    public Map<String, Object> selectStoreBasicMessage(Long storeId) {
        HashMap<String, Object> storeMap = new HashMap<>(4);
        Store store = storeMapper.selectByPrimaryKey(storeId);
        storeMap.put("storeName", store.getStoreName());
        storeMap.put("storeLogo", store.getStoreLogo());

        //Todo 查询店铺评分,好评率,今日销量:18  累计销量:999  本月更新商品:99
        Set<String> keys = RedisUtil.getKeys("remark:*:*:" + storeId + ":*", redisTemplate);
        Iterator<String> iterator = keys.iterator();
        Long total = 0L;
        Long fiveScore = 0L;
        while (iterator.hasNext()) {
            String next = iterator.next();
            Object o = redisTemplate.opsForValue().get(next);
            Map map = JsonUtil.stringToObject(String.valueOf(o), Map.class);
            Long rank = Long.valueOf(map.get("rank").toString());
            if (rank == 5L){
                fiveScore++;
            }
            total = total +rank;
        }
        Long score = total/keys.size();
        Double goodScoreRate = Double.parseDouble(score.toString())/5;
        storeMap.put("storeScore", score);
        storeMap.put("goodCommentRate", goodScoreRate);
        return storeMap;
    }


}
